﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using YoucaiReader.Entities;

/**
 * 创建时间：2014/10/12 10:18:32
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 * Description：断章
 */
namespace YoucaiReader.Helper
{
    internal class ChapterParser
    {
        private List<int> chapterIndexList = new List<int>();
        private List<string> chapterNameList = new List<string>();
        private string FileBuf;
        private string FileName;
        private bool isChapterParser;
        private MatchCollection myMatches;
        private Regex myRegex;
        private string regularExpressions = @"第\s{0,6}([一二三四五六七八九十零百千万壹贰叁肆伍陆柒捌拾0-9１２３４５６７８９０]{1,9})\s{0,6}[章回卷篇]";

        public ChapterParser(string fileName)
        {
            this.FileName = fileName;
            if (Typesetting.getBookBuf().Length > 0)
            {
                this.isChapterParser = true;
                this.FileBuf = Typesetting.getBookBuf();
                this.myRegex = new Regex(this.regularExpressions, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            }
            else
            {
                this.isChapterParser = false;
            }
        }

        public bool Parser()
        {
            if (this.isChapterParser)
            {
                this.myMatches = this.myRegex.Matches(this.FileBuf, 0);
                string s = "";
                if (this.myMatches.Count > 0)
                {
                    for (int i = 0; i < this.myMatches.Count; i++)
                    {
                        int count = this.FileBuf.IndexOf('\n', this.myMatches[i].Index) - this.myMatches[i].Index;
                        char[] destination = new char[count];
                        this.FileBuf.CopyTo(this.myMatches[i].Index, destination, 0, count);
                        new BookChapterListData();
                        object obj2 = s + new string(destination).Replace('\r', ' ').Replace('\n', ' ');
                        s = string.Concat(new object[] { obj2, "\n", this.myMatches[i].Index, "\r" });
                    }
                }
                else
                {
                    s = "第一章\n0\r";
                }
                IsolatedStorageFileStream stream = App.QQReader_StorageFile.StorageFile.OpenFile(App.ReaderFileName + "chapterList", FileMode.Create, FileAccess.ReadWrite);
                byte[] bytes = Encoding.UTF8.GetBytes(s);
                stream.Write(bytes, 0, bytes.Length);
                stream.Flush();
                stream.Close();
            }
            return this.isChapterParser;
        }
    }
}
